<template>
  <div class="tablearea">
    <!-- 搜索插件 -->
    <search-bar :formOptions="formOptions"
                :searchDialog="searchDialog"
                :clearQueryForm="clearQueryForm"
                @controlSearchDialog="controlSearchDialog"
                @onSearch="onSearch"></search-bar>
    <!-- 表格 -->
    <!-- 工具栏按钮插件 -->
    <tool-bar @controlSearchDialog="controlSearchDialog"
              @edit_handler="edit_handler"
              @add_handler="add_handler"
              @selectAll="selectAll"
              @selectNotAll="selectNotAll"
              @delete="delete_handler"></tool-bar>
    <!-- 表格插件 -->
    <el-table ref="table"
              :data="tableData"
              style="width: 100%;color: black;margin-top:5px"
              :height="tablehight"
              :cell-style="{padding: '2px'}"
              :header-cell-style="{padding: '2px'}"
              :header-row-style="{color:'black'}"
              tooltip-effect="dark"
              type="index"
              show-header
              stripe
              border
              default-expand-all
              row-key="id">
      <!-- 序号和勾选框 -->
      <el-table-column type="selection"
                       width="50">
      </el-table-column>
      <el-table-column v-if="indexId"
                       type="index"
                       :index="indexMethod"
                       width="55"
                       :label="$t('common.serialNumber')">
      </el-table-column>
      <!-- 动态列 -->
      <el-table-column v-for="item in columnList"
                       :key="item.prop"
                       :label="$t(item.label)"
                       :prop="item.prop"
                       :width="item.width"
                       :show-overflow-tooltip="true">
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column align="center"
                       width="130">
        <template slot="header">
          <span>操作列</span>
        </template>
        <template slot-scope="scope">
          <el-button-group>
            <el-button class="my-btn"
                       size="mini"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button class="my-btn"
                       size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页信息 -->
    <el-pagination style="float:right;margin-top:5px"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentPageChange"
                   :current-page="this.pageData.pageNumber"
                   :page-sizes="[10, 20, 30, 40]"
                   :page-size="this.pageData.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="totalRow">
    </el-pagination>

    <!-- 新增和修改 -->
    <save-edit-form :formOptions="formOptions"
                    :addEditDialogShow="addEditDialogShow"
                    :addEditData="addEditData"
                    @controlAddEditDialog="controlAddEditDialog"
                    @addEditOk="addEditOk"></save-edit-form>

  </div>
</template>

<script>
import * as Tools from '../search/tools'
import ToolBar from './toolbar-plugin.vue'
import SearchBar from '../search/search-plugin.vue'
import SaveEditForm from './add-edit-plugin.vue'
import { requireData } from '../../utils/common'

export default {
  components: {
    ToolBar,
    SearchBar,
    SaveEditForm
  },
  props: {
    // 是否展示序号
    indexId: false,
    // 表格列
    columnList: Array,
    // 工具栏按钮的 url
    url: Object
  },
  data: function () {
    return {
      // 表格数据
      tableData: [],
      // 需要查询的列
      formOptions: [
        {
          label: '意见内容',
          prop: 'content',
          element: 'el-input'
        },
        {
          label: '类型',
          prop: 'type',
          element: 'el-select',
          options: [
            { label: '给点意见', value: '1' },
            { label: '售后问题', value: '2' }
          ]
        },
        {
          label: '提交时间',
          prop: 'timeRange',
          element: 'el-date-picker'
        }
      ],
      // 是否展示查询条件框
      searchDialog: false,
      // 查询表单数据
      queryFormData: {},
      // 是否清空查询条件的表单数据
      clearQueryForm: false,
      // 分页参数
      pageData: {
        pageSize: 10,
        pageNumber: 0,
        total: 0
      },

      // 新增或者编辑 form 是否展示
      addEditDialogShow: false,
      // 需要编辑的数据
      addEditData: {}
    }
  },
  computed: {
    // 计算表格高度
    tablehight () {
      // 表格的高度自适应
      return window.innerHeight - 180 + 'px'
    },
    // 计算分页数据
    totalRow () {
      return this.pageData.total
    }

  },
  methods: {
    // 表格序号
    indexMethod (index) {
      return index + 1
    },
    // 每页大小改变
    handleSizeChange (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    // 当前页数改变
    handleCurrentPageChange (page) {
      this.pageData.pageNumber = page
      this.getTableData()
    },
    // 改变查询条件是否展示
    controlSearchDialog (val) {
      this.searchDialog = val
      // 组装当前表格的数据为查询列
      this.formOptions = Tools.queryColumns(this.columnList)
    },
    // 控制新增或者编辑
    controlAddEditDialog (showFlag, val) {
      this.addEditData = val
      this.addEditDialogShow = showFlag
      if (val !== undefined) {
        this.formOptions = Tools.initColumnValue(this.columnList, val)
      } else {
        // 清空默认值
        this.formOptions = Tools.resetColumnValue(this.columnList, val)
      }
      this.formOptions = Tools.queryColumns(this.columnList)
    },
    // 获取搜索表单提交的数据
    onSearch (val) {
      this.queryFormData = val
      // 关闭内容查询框
      this.searchDialog = false
      this.getTableData()
      // 清空表单的数据
      this.clearQueryForm = true
    },
    packageLabel (str) {
      let label = this.$t(str.label)
      return label
    },
    // 全选
    selectAll () {
      let that = this
      function splite (data) {
        data.forEach((row) => {
          that.$refs.table.toggleRowSelection(row, true)
          if (row.children && row.children.length > 0) {
            splite(row.children)
          }
        })
      }
      splite(this.tableData)
    },
    // 全不选
    selectNotAll () {
      this.$refs.table.clearSelection()
    },
    // 删除
    delete_handler (id) {
      let url = this.url.delete.url
      let type = this.url.delete.type
      let module = this.url.delete.module
      let deletekey = this.url.deletekey
      let ids = []
      let arr = this.$refs['table'].selection
      if (arr.length === 0 && id === undefined) {
        this.$message.warning('请选择要删除的数据！')
        return
      }
      if (id !== undefined) {
        ids.push(id)
      }
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i]
        ids.push(item[deletekey])
      }
      this.$confirm('确认删除选择的 ' + ids.length + ' 条数据吗？')
        .then(_ => {
          requireData(url, ids, type, module).then(res => {
            if (res.code === 200) {
              this.$message.info(res.message)
              this.pageData.pageNumber = 0
              this.getTableData()
            } else {
              this.$message.error(res.message)
            }
          })
        })
    },
    // 编辑
    handleEdit (index, row) {
      this.controlAddEditDialog(true, row)
    },
    edit_handler () {
      // 获取当前选择的数据进行编辑
      let row = this.$refs['table'].selection[0]
      this.controlAddEditDialog(true, row)
    },
    // 新增
    add_handler () {
      this.controlAddEditDialog(true)
    },
    // 新增或者修改
    addEditOk (val) {
      if (val === undefined) {
        this.$message.warning('请填写表单内容！')
        return
      }
      // this.controlAddEditDialog(false)
      let param = val
      let url = this.url.insert.url
      let type = this.url.insert.type
      let module = this.url.insert.module
      requireData(url, param, type, module).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message)
          this.pageData.pageNumber = 0
          this.addEditDialogShow = false
          this.getTableData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 操作列删除
    handleDelete (index, row) {
      let deletekey = this.url.delete.deletekey
      this.delete_handler(row[deletekey])
    },
    // 获取用户列表
    getTableData () {
      let param = {
        pageSize: this.pageData.pageSize,
        pageNumber: this.pageData.pageNumber,
        queryForm: this.queryFormData
      }
      let paramInUrl = this.url.page.param
      Object.assign(param, paramInUrl)
      let url = this.url.page.url
      let type = this.url.page.type
      let module = this.url.page.module
      requireData(url, param, type, module).then(res => {
        if (res.code === 200) {
          this.tableData = res.data
          this.pageData.total = res.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 刷新
    refreshTable () {
      this.pageData.pageSize = 10
      this.pageData.pageNumber = 0
      this.getTableData()
    }
  },
  created () {
    // 获取 table 的数据
    this.getTableData()
  }
}
</script>
<style scoped>
.tablearea {
  padding: 4px;
}
/* 操作列按钮的样式调整 */
.my-btn {
  padding: 4px 13px;
}
</style>
